package net.vkits.auth.application;

import net.vkits.auth.domain.model.Permission;
import net.vkits.auth.domain.model.Role;
import net.vkits.auth.domain.repository.PermissionRepository;
import net.vkits.auth.domain.repository.RoleRepository;
import net.vkits.common.exceptions.NoSuchRoleExeption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * Created by ethan-liu on 16/5/8.
 */
@Service
public class RoleApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(RoleApplicationService.class);

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private PermissionRepository permissionRepository;

    @Transactional
    public void addRole(String name, String description) {
        Role role = new Role(name, description);
        roleRepository.save(role);
    }

    @Transactional
    public void delRole(Long id) {
        roleRepository.delete(id);
    }

    @Transactional
    public void assignPermission(String name, Set<String> permissionIds) {
        Optional<Role> roleOptional = roleRepository.findByName(name);
        roleOptional.ifPresent(role -> {
            Set<Permission> permissions = new LinkedHashSet<>();
            permissionIds.forEach(id ->
                            permissions.add(permissionRepository.findOne(Long.parseLong(id)))
            );
            role.setPermissions(permissions);
            roleRepository.save(role);
        });
        roleOptional.orElseThrow(NoSuchRoleExeption::new);
    }

    public Page<Role> getRoleList(Pageable pageable) {
        return roleRepository.findAll(pageable);
    }

    public List<Role> getRoleAll() {
        return roleRepository.findAll();
    }
}
